package com.example.aicompositiongrader.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.provider.MediaStore;

import com.google.mlkit.vision.common.InputImage;
import com.google.mlkit.vision.text.Text;
import com.google.mlkit.vision.text.TextRecognition;
import com.google.mlkit.vision.text.TextRecognizer;
import com.google.mlkit.vision.text.chinese.ChineseTextRecognizerOptions;

import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class OcrManager {
    private final TextRecognizer recognizer;
    private final ExecutorService executor;
    private OcrResultListener listener;

    public interface OcrResultListener {
        void onSuccess(String text);
        void onFailure(String error);
    }

    public OcrManager(Context context) {
        // 使用中文识别器
        recognizer = TextRecognition.getClient(new ChineseTextRecognizerOptions.Builder().build());
        executor = Executors.newSingleThreadExecutor();
    }

    public void setListener(OcrResultListener listener) {
        this.listener = listener;
    }

    // 从图片路径识别文字
    public void recognizeTextFromPath(String imagePath) {
        executor.execute(() -> {
            try {
                Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
                if (bitmap == null) {
                    notifyFailure("无法加载图片");
                    return;
                }

                InputImage image = InputImage.fromBitmap(bitmap, 0);
                processImage(image);
            } catch (Exception e) {
                notifyFailure(e.getMessage());
            }
        });
    }

    // 从Uri识别文字
    public void recognizeTextFromUri(Context context, Uri uri) {
        executor.execute(() -> {
            try {
                InputImage image = InputImage.fromFilePath(context, uri);
                processImage(image);
            } catch (IOException e) {
                notifyFailure(e.getMessage());
            }
        });
    }

    // 处理图片识别
    private void processImage(InputImage image) {
        recognizer.process(image)
                .addOnSuccessListener(text -> {
                    String resultText = extractTextFromResult(text);
                    notifySuccess(resultText);
                })
                .addOnFailureListener(e -> {
                    notifyFailure(e.getMessage());
                });
    }

    // 从识别结果中提取文字
    private String extractTextFromResult(Text text) {
        StringBuilder result = new StringBuilder();
        for (Text.TextBlock block : text.getTextBlocks()) {
            for (Text.Line line : block.getLines()) {
                result.append(line.getText()).append("\n");
            }
        }
        return result.toString();
    }

    // 通知成功
    private void notifySuccess(String text) {
        new Handler(Looper.getMainLooper()).post(() -> {
            if (listener != null) {
                listener.onSuccess(text);
            }
        });
    }

    // 通知失败
    private void notifyFailure(String error) {
        new Handler(Looper.getMainLooper()).post(() -> {
            if (listener != null) {
                listener.onFailure(error);
            }
        });
    }

    // 释放资源
    public void close() {
        recognizer.close();
        executor.shutdown();
    }
}